package lsmtree

import (
	"log"
	"lsmtree/config"
	sstable "lsmtree/ssTable"
	"os"
)

// 启动数据库
func Start(con config.Config) {
	if database != nil {
		return
	}
	// 加载配置到内存
	log.Println("Loading a Configuration File")
	config.Init(con)

	// 初始化 DB
	log.Println("Initializing the database")
	initDatabase(con.DataDir)

	log.Println("Preforming background checks....")
	checkMemory()
	database.TableTree.Check()

	// 启动后台线程
	go Check()
	go CompressMemory()
}

func initDatabase(dir string) {
	database = &Database{
		MemTable:  &MemTable{},
		iMemTable: &ReadOnlyMemTables{},
		TableTree: &sstable.TableTree{},
	}

	if _, err := os.Stat(dir); err != nil {
		log.Printf("The %s directory does not exist. The directory is being created\r\n", dir)
		err := os.MkdirAll(dir, 0700)
		if err != nil {
			log.Println("Failed to create the database directory")
			panic(err)
		}
	}

	database.iMemTable.Init()
	database.MemTable.InitMemTree()
	log.Println("Loading all wal.log...")
	database.loadAllWalFiles(dir)
	database.MemTable.InitWal(dir)
	log.Println("Loading database....")
	database.TableTree.Init(dir)
}
